<?php
namespace Home\Controller;
use Think\Controller;
use Think\Verify;
use \Vendor\qq\qqAuth;

class IndexController extends Controller {

    private $pageSize=12;
    public function _empty($method, $args){
        $this->redirect('/');
    }

    public function __construct(){
        parent::__construct();
        /*获取热门推荐*/
        if(!S('hotArticle')){
            $hotArticle=M('articles')->field('title,id,cover,views')->limit(5)
            ->where('is_banner=0 and status=1')->order('views desc')->select();
            S('hotArticle',$hotArticle,24*3600);
            $this->hotArticle=$hotArticle;
        }else{
            $this->hotArticle=S('hotArticle');
        }
		//获取友情链接
		 if(!S('links')){
            $links=M('links')->where('status=1')->select();

            S('links',$links,24*3600);
            $this->links=$links;
        }else{
            $this->links=S('links');
        }
        /*每日一句*/
        if(!S('translation')){
            $content=file_get_contents('http://open.iciba.com/dsapi/?date='.date('Y-m-d'));
            $translation=str_replace('：','',strstr(json_decode($content,true)['translation'],'：'));
            S('translation',$translation,24*3600);
            $this->translation=$translation;
        }else{
            $this->translation=S('translation');
        }
        /*分类*/
        if(!S('categories')){
            $categories=M('categories')->where('status=1')->select();
            S('categories',$categories,24*3600);
            $this->categories=$categories;
        }else{
            $this->categories=S('categories');
        }
        /*归档*/
        if(!S('archives')){
            $sql="SELECT FROM_UNIXTIME(create_time,'%Y-%m') month,COUNT(*) count FROM mf_articles WHERE status=1 GROUP BY month";
            $archives=M()->query($sql);
            S('archives',$archives,24*3600);
            $this->archives=$archives;
        }else{
            $this->archives=S('archives');
        }
        
        /*菜单*/
        if(!S('menus')){
            $menus=M('menus')->where('status=1')->select();
            S('menus',$menus,24*3600);
            $this->menus=$menus;
        }else{
            $this->menus=S('menus');
        }
    }

    /**
     * 验证码
     */
    public function verify(){
        $cfg=array(
            'imageH'=>34,       //验证码高度
            'imageW'=>120,      //验证码宽度
            'fontSize'=>16,     //验证码字体大小
            'length'=>4,        //验证码字符串长度
            'fontttf'=>'5.ttf'  //验证码字体
        );
        $very=new Verify($cfg);
        $very->entry();
    }
	//下载
	public function down(){
		if(IS_AJAX){
            $verify=new Verify();
            if(!$verify->check(I('post.code'))){
                $this->ajaxReturn(array('status'=>0,'msg'=>'验证码错误！'));
            }else{
				$this->ajaxReturn(array('status'=>1));
			}
		}
		$this->display();
	}
	public function downzip(){
		downfile('mfblog.zip');
		if(!F('num')['num']){
			$data['num']=1;
		}else{
			$data['num']=F('num')['num']+1;
		}
		F('num',$data);
		if(F('webSet')['Semail']==1){
                    // 给我发邮件通知
                    $myEmail=M('user')->field('email')->limit(1)->select()[0]['email'];
                    if(!empty($myEmail)){
                        $content=date('Y-m-d H:i:s',time()).',有人下载你的源码,目前总计被下载'.F('num')['num'].'次';
                        sendMail($myEmail,'下载通知',$content);
                    }
                }
		return;
	}
    /**
     * 博客首页
     */
    public function index(){
        $where=array('a.status'=>1,'a.is_banner'=>'');
        $articleCount=M("articles")->alias('a')->where($where)->count();
        $newArticles=$this->selectArticle($where);
        /*本周热门*/
        if(!S('weekHot')){
            $weekHot=M('articles')->field('title,id,cover')->where('is_banner=0 and status=1')->order('likes desc')->limit(5)->select();
            S('weekHot',$weekHot,24*3600);
            $this->weekHot=$weekHot;
        }else{
            $this->weekHot=S('weekHot');
        }

        /*首页banner推荐文章*/
        if(!S('bannerArticle')){
            $sql="SELECT title,id,banner FROM mf_articles WHERE is_banner=1 and status=1 ORDER BY RAND() LIMIT 6";
            $bannerArticle=M()->query($sql);
            S('bannerArticle',$bannerArticle,12*3600);
            $this->bannerArticle=$bannerArticle;
        }else{
            $this->bannerArticle=S('bannerArticle');
        }

        /*用户名*/
        if(!S('user')){
            $user=M('user')->field('username')->limit(1)->find()['username'];
            S('user',$user,24*3600);
            $this->user=$user;
        }else{
            $this->user=S('user');
        }
        $this->isIndex='true';
        $this->at='';
        $this->newArticles=$newArticles;
        $this->pageCount=ceil($articleCount/$this->pageSize);
        $this->title=F('webSet')['webtitle'];
        $this->display();
    }

    /**
     * 文章页
     */
    public function article($id){
        cookie('_url',$_SERVER['REQUEST_URI'],3600);
        if(!empty($id)){
            $article=M('articles')->alias('a')
            ->field('a.id,a.title,a.tags,a.likes,a.views,a.cover,a.create_time,c.category,ac.content,a.category_id')
            ->join('__ARTICLE_CONTENTS__ ac ON a.content_id=ac.id','LEFT')->join('__CATEGORIES__ c on a.category_id=c.id')
            ->where('a.status=1 and a.id='.$id)->find();
            if($article){
                $article['views']+=1;
                M('articles')->save(array('id'=>$article['id'],'views'=>$article['views']));
                $this->title=$article['title'];
                /*上一篇，下一篇*/
                $this->prevNext=$this->getPrevNext($id);
                
                if(!S('user')){
                    $user=M('user')->field('username')->limit(1)->find()['username'];
                    S('user',$user,24*3600);
                    $this->user=$user;
                }else{
                    $this->user=S('user');
                }
                /*获得评论*/
                if(F('webSet')['barrage']==1){
                    $comments=M('comments')->field('id,nickname,is_admin,comment,avatar,to')->where('article_id='.$id)->order('id desc')->limit(20)->select();
                    if(!empty($comments)){
                        $jsonComments=array();
                        foreach ($comments as $key => $value) {
                            if($value['to']!=0 && $value['is_admin']==1){
                                /*站长*/
                                $img='/Public/static/home/images/readerAvatar.png';
                                $value['nickname']='站长';
                            }else{
                                if(F('webSet')['qqLogin']==1){
                                    $img=$value['avatar'];
                                }else{
                                    $img="/Public/static/home/images/avatars/".($value['id']%10).".jpg";
                                }    
                            }
                            $jsonComments[$key]=array('close'=>0,'info'=>$value['nickname'].' ：'.$value['comment'],'img'=>$img);
                        }
                    }    
                }
                $this->isIndex='false';
                $this->at=$article['title'];
                $this->jsonComments=json_encode($jsonComments);
                $this->article=$article;
                $commentCount=M("comments")->where('article_id='.$id)->count();
                $this->pageCount=ceil($commentCount/$this->pageSize);
                $this->recommendations=$this->recommendation($id);
                $this->display();
            }else{
                \Think\Log::record('Visited articles that did not exist','WARN',true);
                /*跳转到404*/
                header( " HTTP/1.0  404  Not Found" );
                // $this->error('文章不存在');
            }
        }else{
            /*跳转到404*/
            header( " HTTP/1.0  404  Not Found" );
            // $this->error('访问出错');
        }
    }

    /**
     * 获取随机推荐文章
     * @param  [int] $id [文章id]
     * @return [array]     [推荐文章]
     */
    private function recommendation($id){
        //随机获取推荐id
        $articleMinId=M('articles')->field('id')->order('id asc')->limit(1)->find()['id'];
        $articleMaxId=M('articles')->field('id')->order('id desc')->limit(1)->find()['id'];
        $ids='';
        for($i=0;$i<16;$i++){
            $ids.=mt_rand($articleMinId,$articleMaxId).',';
        }
        $ids=trim($ids,',');
        /*获取分类id*/
        $category_id=M('articles')->field('category_id')->find($id)['category_id'];
        $recommendations=M('articles')->field('title,id,cover')
        ->where("`id` in (".$ids.") and category_id=".$category_id.' and is_banner=0 and id!='.$id)->limit(8)->select();
        return $recommendations;
    }

    /**
     * 获取上一篇，下一篇
     * @param  [int] $id [文章id]
     * @return [array]     [上下篇]
     */
    private function getPrevNext($id){
        $prev=M('articles')->where('status =1 and `is_banner`=0 and id<'.$id)
            ->limit(1)->order('create_time desc')->field('id,title')->select();
        $next=M('articles')->where('status =1 and `is_banner`=0 and id>'.$id)
            ->limit(1)->field('create_time,title')->field('id,title')->select();
        if($prev){
            $prev=$prev[0];
        }
        if($next){
            $next=$next[0];
        }
        return array($prev,$next);
    }

    /**
     * 文章点赞
     */
    public function likePlus(){
        if(IS_AJAX && !empty(I('post.id'))){
            $articleLikes=M('articles')->field('likes')->find(I('post.id'))['likes'];
            $articleLikes+=1;
            if(M('articles')->save(array('id'=>I('post.id'),'likes'=>$articleLikes))){
                $this->ajaxReturn(array('status'=>1,'msg'=>'点赞成功'));
            }else{
                $this->ajaxReturn(array('status'=>0,'msg'=>'点赞失败'));
            }
        }else{
            /*跳转到404*/
            \Think\Log::record('Incorrect access','WARN',true);
            header( " HTTP/1.0  404  Not Found" );
            // $this->error('访问出错');
        }
    }

    /**
     * 友情链接
     */
    public function links(){
        if(IS_AJAX){
            $verify=new Verify();
            if(!$verify->check(I('post.code'))){
                $this->ajaxReturn(array('status'=>0,'msg'=>'验证码错误！'));
            }
            $data=I('post.');
            if(strpos($data['link'],'http://')!==0){
                $data['link']='http://'.$data['link'];
            }
            $data['create_time']=time();
            $data['status']=0;
            if(M('links')->add($data)){
                if(F('webSet')['Semail']==1){
                    // 给我发邮件通知
                    $myEmail=M('user')->field('email')->limit(1)->select()[0]['email'];
                    if(!empty($myEmail)){
                        $content='有人提交友链啦，<br>博客名：'.$data['name'].'，<br>描述：'.$data['describe'].'，<br>地址：'.$data['link'].'<br>快登陆后台查看吧';
                        sendMail($myEmail,'友链提交通知',$content);
                    }
                }
                $this->ajaxReturn(array('status'=>1,'msg'=>'提交成功，你会收到审核结果'));
            }else{
                $this->ajaxReturn(array('status'=>0,'msg'=>'提交失败'));
            }
        }
        $links=M('links')->where('status=1')->select();
		S('links',$links,24*3600);
        $this->links=$links;
        $this->isIndex='true';
        $this->at='';
        $this->title='友情链接';
        $this->display();
    }

    /**
     * 关于我
     */
    public function about(){
        $about=M('user')->limit(1)->field('description,qq,github,avatar,gitosc,email,weibo,weibo_num,username')->find();
        $this->about=$about;
        $this->isIndex='true';
        $this->at='';
        $this->title='关于我';
        $this->display();
    }
    /**
     * 留言墙
     */
    public function messageWall(){
        $data=I('post.');
        if(IS_AJAX && isset($data['message'])){
            /*判断是否登录*/
            if(F('webSet')['qqLogin']==1){
                $openid=session('openid');
                if(empty($openid)){
                    $this->ajaxReturn(array('status'=>0,'msg'=>'您未登录'));
                }                
            }
            if(I('post.nickname')==''){
                $this->ajaxReturn(array('status'=>0,'msg'=>'昵称不能为空'));
            }
            if(!empty($data['email'])){
                $pattern = "/^([0-9A-Za-z\\-_\\.]+)@([0-9a-z]+\\.[a-z]{2,3}(\\.[a-z]{2})?)$/i";
                if(!preg_match( $pattern, $data['email'] ) ){
                    $this->ajaxReturn(array('status'=>0,'msg'=>'邮箱格式不正确'));
                }
            }

            $verify=new Verify();
            if(!$verify->check(I('post.code'))){
                $this->ajaxReturn(array('status'=>0,'msg'=>'验证码错误！'));
            }
            $data['create_time']=time();
            // $data['to']=I('post');
            $data['browser']=getBrowser();
            $data['systemOS']=getOs();
            $data['avatar']=session('visitor')['figureurl_1'];
            $data['vid']=session('vid');
            // var_dump($data);exit;
            if($mid=M('messages')->add($data)){
                $this->ajaxReturn(array('status'=>1,'mid'=>$mid,'systemos'=>$data['systemOS'],
                    'browser'=>$data['browser'],'create_time'=>date('Y-m-d H:i:s')));
            }else{
                $this->ajaxReturn(array('status'=>0,'msg'=>'提交失败'));
            }
        }
        cookie('_url',$_SERVER['REQUEST_URI'],3600);
        $page=I('get.p')?I('get.p'):1;
        $messageCount=M("messages")->count();
        $messages=M('messages')->order('id desc')->limit(($page-1)*$this->pageSize,$this->pageSize)->select();
        /*查询回复者昵称*/
        foreach ($messages as $key => $message) {
            if($message['to']!=0){
                $info=M('messages')->field('is_admin,nickname,avatar,message,systemOS,browser,create_time,upm,downm,id')->find($message['to']);
                $messages[$key]['replay_id']=$info['id'];
                $messages[$key]['replay']=$info['nickname'];
                $messages[$key]['replay_a']=$info['avatar'];
                $messages[$key]['replay_admin']=$info['is_admin'];
                $messages[$key]['replay_upm']=$info['upm'];
                $messages[$key]['replay_downm']=$info['downm'];
                $messages[$key]['replay_msg']=$info['message'];
                $messages[$key]['replay_systemos']=$info['systemos'];
                $messages[$key]['replay_browser']=$info['browser'];
                $messages[$key]['replay_create_time']=$info['create_time'];
            }
        }

        /*获得弹幕*/
        if(F('webSet')['barrage']==1){
            $tmessages=M('messages')->field('id,nickname,is_admin,message,avatar,to')->order('id desc')->limit(20)->select();
            if(!empty($tmessages)){
                $jsonMessages=array();
                foreach ($tmessages as $key => $value) {
                    if($value['to']!=0 && $value['is_admin']==1){
                        /*站长*/
                        $img='/Public/static/home/images/readerAvatar.png';
                        $value['nickname']='站长';
                    }else{
                        if(F('webSet')['qqLogin']==1){
                            $img=$value['avatar'];
                        }else{
                            $img="/Public/static/home/images/avatars/".($value['id']%10).".jpg";
                        }
                    }
                    $jsonMessages[$key]=array('close'=>0,'info'=>$value['nickname'].' ：'.$value['message'],'img'=>$img);
                }
            }
        }
        $this->jsonMessages=json_encode($jsonMessages);
        $this->messages=$messages;
        $this->title="留言墙";
        $this->isIndex='true';
        $this->at='';
        $this->pageCount=ceil($messageCount/$this->pageSize);
        $this->display();
    }

    /**
     * 文章列表页
     */
    public function articles(){
        $keywords=I('get.');
        if(isset($keywords['title'])){
            /*按照名称搜索*/
            $where=array('a.status'=>1,'a.title'=>array('like','%'.trim($keywords['title']).'%'));
            $this->flag=1;
            $this->title='搜索“'.$keywords['title'].'”的文章';
        }
        if(isset($keywords['tag'])){
            /*按照标签搜索*/
            $where=array('a.status'=>1,'a.tags'=>array('like','%'.$keywords['tag'].'%'));
            $this->title='包含“'.$keywords['tag'].'”标签的文章';
        }
        if(isset($keywords['cid'])){
            /*按照分类搜索*/
            $category=M('categories')->where('status=1')->field('category')->find($keywords['cid'])['category'];
            $category=empty($category)?'未知分类':$category;
            $where=array('a.status'=>1,'a.category_id'=>$keywords['cid']);
            $this->title='“'.$category.'”分类的文章';
        } 
        if(isset($keywords['month'])){
            /*按照月份查看*/
            $temp=explode('-',$keywords['month']);
            $year=$temp[0];
            $month=$temp[1];
            $startTime=strtotime($keywords['month']);
            $endTime=strtotime($year.'-'.($month+1));
            $where['a.create_time']=array('between',array($startTime,$endTime));
            $where['a.status']=1;
            $this->title=$keywords['month'].'月的文章';
        }
        $articleCount=M("articles")->alias('a')->where($where)->count();
        $articles=$this->selectArticle($where);
        $this->pageCount=ceil($articleCount/$this->pageSize);
        $this->articles=$articles;
        $this->user=M('user')->field('username')->limit(1)->find()['username'];
        $this->isIndex='true';
        $this->at='';
        $this->display();
    }

    /**
     * 搜索文章列表
     * @param  [array] $where [查询条件数组]
     * @return [array]        [文章数组]
     */
    private function selectArticle($where){
        $page=I('get.p')?I('get.p'):1;
        return M('articles')->alias('a')
            ->field('a.id,a.title,a.tags,a.likes,a.views,a.cover,a.create_time,c.category,ac.content,a.category_id')
            ->join('__ARTICLE_CONTENTS__ ac ON a.content_id=ac.id','LEFT')->join('__CATEGORIES__ c on a.category_id=c.id')
            ->where($where)->order('a.create_time desc')->limit(($page-1)*$this->pageSize,$this->pageSize)->select();
    }

    /**
     * 添加评论
     */
    public function addComment(){
        if(IS_AJAX){
            /*判断是否登录*/
            if(F('webSet')['qqLogin']==1){
                $openid=session('openid');
                if(empty($openid)){
                    $this->ajaxReturn(array('status'=>0,'msg'=>'您未登录'));
                }                
            }
            if(I('post.nickname')==''){
                $this->ajaxReturn(array('status'=>0,'msg'=>'昵称不能为空'));
            }
            $data=I('post.');
            if(!empty($data['email'])){
                $pattern = "/^([0-9A-Za-z\\-_\\.]+)@([0-9a-z]+\\.[a-z]{2,3}(\\.[a-z]{2})?)$/i";
                if(!preg_match( $pattern, $data['email'] ) ){
                    $this->ajaxReturn(array('status'=>0,'msg'=>'邮箱格式不正确'));
                }
            }
            $verify=new Verify();
            if(!$verify->check(I('post.code'))){
                $this->ajaxReturn(array('status'=>0,'msg'=>'验证码错误！'));
            }
            
            $data['create_time']=time();
            // $data['to']=0;
            $data['browser']=getBrowser();
            $data['systemos']=getOs();
            $data['avatar']=session('visitor')['figureurl_1'];
            $data['vid']=session('vid');
            if($sid=M('comments')->add($data)){
                $this->ajaxReturn(array('status'=>1,'sid'=>$sid,'systemos'=>$data['systemos'],
                    'browser'=>$data['browser'],'create_time'=>date('Y-m-d H:i:s')));
            }else{
                $this->ajaxReturn(array('status'=>0,'msg'=>'提交失败'));
            }
        }else{
            \Think\Log::record('Incorrect access','WARN',true);
            header( " HTTP/1.0  404  Not Found" );
        }
    }

    /**
     * 获取评论接口
     */
    public function getComments(){
        if(IS_AJAX){
            $page=I('post.p')?I('post.p'):1;
            $comments=M('comments')->where('article_id='.I('post.acid'))->order('id desc')->limit(($page-1)*$this->pageSize,$this->pageSize)->select();
            /*查询回复者昵称*/
            foreach ($comments as $key => $message) {
                if($message['to']!=0){
                    $info=M('comments')->field('nickname,avatar,comment,systemos,browser,create_time,upc,downc,is_admin')->find($message['to']);
                    $comments[$key]['replay']=$info['nickname'];
                    $comments[$key]['replay_a']=$info['avatar'];
                    $comments[$key]['replay_upc']=$info['upc'];
                    $comments[$key]['replay_downc']=$info['downc'];
                    $comments[$key]['replay_admin']=$info['is_admin'];
                    $comments[$key]['replay_com']=$info['comment'];
                    $comments[$key]['replay_systemos']=$info['systemos'];
                    $comments[$key]['replay_browser']=$info['browser'];
                    $comments[$key]['replay_create_time']=date('Y-m-d H:i:s',$info['create_time']);
                }
                $comments[$key]['create_time']=date('Y-m-d H:i:s',$comments[$key]['create_time']);
            }
            $this->ajaxReturn($comments);
        }else{
            \Think\Log::record('Incorrect access','WARN',true);
            header( " HTTP/1.0  404  Not Found" );
        }
    }

    /**
     * 本站标签
     */
    public function tags(){
        $tags=M('articles')->field('tags')->where('status=1')->select();
        $tagStr='';
        foreach ($tags as $key => $tag) {
            $tagStr.=','.$tag['tags'];
        }
        $this->tags=strtolower(trim($tagStr,','));
        $this->title='本站标签';
        $this->isIndex='true';
        $this->at='';
        $this->display();
    }
    
    /**
     * 保存登录者信息
     */
    public function saveVisitor(){
        $openid=session('openid');
        if(isset($openid)){
            //查询openid是否已经存在
            $res=M('Visitors')->where('openid="'.$openid.'"')->find();
            $data=array();
            $qqlogin=new qqAuth(F('webSet')['appid'],F('webSet')['appkey'],F('webSet')['callback']);
            $visitor=$qqlogin->getUserInfo();
            session('visitor',$visitor);
            $data['openid']=$openid;
            $data['gender']=$visitor['gender'];
            $data['nickname']=$visitor['nickname'];
            $data['province']=$visitor['province'];
            $data['figureurl']=$visitor['figureurl_1'];
            $data['birthyear']=$visitor['year'];
            $data['city']=$visitor['city'];
            $data['login_time']=time();
            if($res){//更新
                $data['id']=$res['id'];
                $a=M('Visitors')->save($data);
                session('vid',$res['id']);
            }else{//添加
                $vid=M('Visitors')->add($data);//返回值不是插入id原因是这个表多个主键
                session('vid',$vid);//记录id便于以后存数据库
            }
        }
        //返回上一页
        $this->redirect(str_replace('.html','',cookie('_url')));
    }

    /**
     * 退出登录
     */
    public function logout(){
        session('visitor',null);
        session('openid',null);
        session('vid',null);
        $this->redirect(str_replace('.html','',cookie('_url')));
    }

    /**
     * QQ登陆
     */
    public function qqLogin(){
        if(F('webSet')['qqLogin']==1){
            $qqlogin=new qqAuth(F('webSet')['appid'],F('webSet')['appkey'],F('webSet')['callback']);
            $qqlogin->qqLogin();
        }else{
            \Think\Log::record('Incorrect access;Not open QQ login','WARN',true);
            $this->error('未开启qq登陆');
        }
    }

    /**
     * QQ登陆回调函数
     */
    public function qqLoginCallback(){
        if(F('webSet')['qqLogin']==1){
            $qqlogin=new qqAuth(F('webSet')['appid'],F('webSet')['appkey'],F('webSet')['callback']);
            $qqlogin->qqCallback();
            $qqlogin->getOpenid();
            echo "<script>opener.location.href='/index/saveVisitor.html';window.close();</script>";
        }else{
            \Think\Log::record('Incorrect access;Not open QQ login','WARN',true);
            $this->error('未开启qq登陆');
        }
    }

    /**
     * 点赞或者点踩
     */
    function commentUpDow(){
        if(IS_AJAX){
            if(I('post.m')==1){
                $m=M('messages');
                $up='upm';
                $down='downm';
            }else{
                $m=M('comments');
                $up='upc';
                $down='downc';
            }
            if(I('post.s')==1){
                $res=$m->where('id='.I('post.id'))->setInc($up,1); 
            }else{
                $res=$m->where('id='.I('post.id'))->setInc($down,1); 
            }
            if($res){
                $this->ajaxReturn(array('status'=>1,'msg'=>'操作成功'));
            }else{
                $this->ajaxReturn(array('status'=>0,'msg'=>'操作失败'));
            }
        }else{
            header( " HTTP/1.0  404  Not Found" );
        }
    }

    /**
     * 从gitoschina上获取commit记录
     */
    public function getGitCommits(){
        if(IS_AJAX){
            $page=I('get.p')?I('get.p'):1;
            $commits=file_get_contents('http://git.oschina.net/api/v5/repos/mengfan1988/mfblog/commits?access_token=fe62d5be71ba8ad66e64d42072ed4940&page='.$page.'&per_page=40');
            $this->ajaxReturn(json_decode($commits));
        }else{
            $this->isIndex='true';
            $this->at='';
            $this->title='博客更新记录';
            $this->display('getgitcommits');
        }
    }
}